package controllers;

import helpers.IdUniqueHelper;
import helpers.NumberHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.ArticleModel;
import systems.ConfigSystem;

import entities.Article;
import entities.SiteConfig;
import entities.User;
import forms.ArticleForm;
import forms.CaptchaForm;

public class SubmitArticleServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		//Get User
		User user = (User) request.getAttribute("user_logged_in");
		
		String url = (String) request.getParameter("url");
		
		TreeMap check = new TreeMap();
		
		String language = (String) request.getAttribute("language");
		if (language == null || language.isEmpty()) {
			language = "en";
		}
		
		Article article = new Article();
		article.setLanguage(language);
		
		
		request.setAttribute("check", check);
		request.setAttribute("article", article);
		request.setAttribute("url", url);
		try {
			request.getRequestDispatcher("/pages/submit_article.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String url = (String) request.getParameter("url");
		
		String language = (String) request.getAttribute("language");
		if (language == null || language.isEmpty()) {
			language = "en";
		}
		
		ArticleModel articleModel = ArticleModel.getInstance();
		Article article = new Article();
		article.setLanguage(language);
		
		SiteConfig siteConfig = ConfigSystem.getConfigs();
		
		TreeMap form = ArticleForm.checkValid(request, article);
		TreeMap check = (TreeMap) form.get("checkValid");
		article = (Article) form.get("article");
		
		if (check.size() == 0) {
		
			article.setId(IdUniqueHelper.getId());
			article.setAuthKey(IdUniqueHelper.getId());
			articleModel.insert(article);
			request.setAttribute("success", "Submit article success with id " + article.getId());
			
			article = new Article();
		}
		
		request.setAttribute("check", check);
		request.setAttribute("article", article);
		request.setAttribute("url", url);
		try {
			request.getRequestDispatcher("/pages/submit_article.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}	
